package com.example.myokhttp;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private final static String TAG = MainActivity.class.getSimpleName();
    private Button btnGet,btnPost;
    private ImageView imageView;
    private HandlerThread handlerThread;
    //接收 子线程消息 处理UI界面
    private Handler handler ;

//    private String url ="https://www.toopic.cn/public/uploads/small/1643009966127164300996671.jpg";
    private String url="http://www.gege686.com:8080/hrm/images/main/tu.jpg";
     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

          handlerThread = new HandlerThread("MyHandlerThread");
         handlerThread.start();
         handler = new Handler(handlerThread.getLooper()){
             @Override
             public void handleMessage(@NonNull Message msg) {
                 super.handleMessage(msg);

                 Log.e(TAG,"-----------handleMessage-------"+(String)msg.obj);
                 Log.e(TAG,"当前线程--ThreadID---"+Thread.currentThread().getId()+"--ThreadName---"+Thread.currentThread().getName());
                 Log.e(TAG,"主线程----ThreadID-"+getMainLooper().getThread().getId()+"----ThreadName"+getMainLooper().getThread().getName());
                 /** TODO 这里报错！*/
               Toast.makeText(MainActivity.this,"-错误信息-"+msg.obj,Toast.LENGTH_SHORT).show();

             }
         };

        btnGet = findViewById(R.id.btn_get);
        btnPost = findViewById(R.id.btn_post);

         imageView = findViewById(R.id.tv_content);

        //事件
        btnGet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                get();
            }


        });

        btnPost.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                post();
            }
        });




    }

    /**
     * 异步get 请求
     * */
    private void get() {
        new Thread(){
            @Override
            public void run() {
                //1. 获取okhttp对象 客户端
                OkHttpClient client = new OkHttpClient.Builder().build();

                // 2. 构建request请求对象
                Request request = new Request.Builder()
                        .url(url)
                        .get()  //默认get请求 可以不写
                        .build();
                // 3. 构建 Call对象
                Call call = client.newCall(request);
                //        call.request(); 同步get

                // 4. 异步 发送请求
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        //失败
                        Log.e("TAG","失败"+e.getMessage());
//                textView.setText("失败--"+e.getMessage());
//                        //1. 通过handler 处理主线UI
                        Message message = new Message();

                        message.obj = e.getMessage();
                        handler.handleMessage(message);
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        //成功
//                        String result = response.body().string();
                        //把图片转成流
                       InputStream inputStream = response.body().byteStream();
                      Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
//
//                        //1. 通过handler 处理主线UI
//                        Message message = new Message();
//                        message.what=0x110;
//                        message.obj = result;
//                        handler.handleMessage(message);

                        //textView.setText(result); 报错 子线程不能操作主线程ui

                        // 2.或者子线程处理主线程 UI
                new Thread(){
                    @Override
                    public void run() {
                        Looper.prepare();
                        MainActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                imageView.setImageBitmap(bitmap);
                            }
                        });
                        Looper.loop();
                    }
                }.start();
                    }
                });
            }
        }.start();

    }

    private void post() {

        //1. 获取okhttp对象 客户端
        OkHttpClient client = new OkHttpClient.Builder().build();

        //form
        RequestBody body = new FormBody.Builder()
                .add("loginName","admin")
                .add("password","123456789")
                .build();

        //3 创建请求
        Request request = new Request.Builder()
                .url("http://www.gege686.com:8080/api/")
                .addHeader("contentType","application/text;charset=UTF-8")
                .post(body)
                .build();

        //4 .回调参数
        Call call =client.newCall(request);
        // 5 发请求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                //失败
                // 2.或者子线程处理主线程 UI
                new Thread(){
                    @Override
                    public void run() {
                        Looper.prepare();
                        MainActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this,"error"+e.getMessage(),Toast.LENGTH_SHORT).show();
                            }
                        });
                        Looper.loop();
                    }
                }.start();
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                //成功
                String result = response.body().string();
                // 2.或者子线程处理主线程 UI
                new Thread(){
                    @Override
                    public void run() {
                        Looper.prepare();
                        MainActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                               Toast.makeText(MainActivity.this,"success"+result,Toast.LENGTH_SHORT).show();
                            }
                        });
                        Looper.loop();
                    }
                }.start();

            }
        });
    }



}